package org.example.client

import org.example.common.{Logging, Pattern}
import scalikejdbc.{ConnectionPool, ConnectionPoolSettings, NamedDB, SQL}

/**
 * 数据库客户端
 */
object DbClient extends Pattern with Logging {

  //初始化数据库
  def init(poolName: String, driver: String, url: String, username: String, password: String): Unit = {
    if (!ConnectionPool.isInitialized(Symbol(poolName))) {
      Class.forName(driver)
      //val settings = ConnectionPoolSettings(initialSize = 5,maxSize = 10,connectionTimeoutMillis = 3000L)
      val settings = ConnectionPoolSettings(initialSize = 5, maxSize = 10, connectionTimeoutMillis = 3000L, validationQuery = "select 1")
      ConnectionPool.add(Symbol(poolName), url, username, password, settings)
      info(s"Initialize connection pool：$poolName")

    }
  }

  //初始化数据库
  def init(poolName: String, driver: String, url: String, username: String, password: String, size: Int, maxSize: Int): Unit = {
    if (!ConnectionPool.isInitialized(Symbol(poolName))) {
      Class.forName(driver)
      //val settings = ConnectionPoolSettings(initialSize = 5,maxSize = 10,connectionTimeoutMillis = 3000L)
      val settings = ConnectionPoolSettings(initialSize = size, maxSize = maxSize, connectionTimeoutMillis = 3000L, validationQuery = "select 1")
      ConnectionPool.add(Symbol(poolName), url, username, password, settings)
      info(s"Initialize connection pool：$poolName")

    }
  }

  //使用数据库
  def usingDB[A](poolName: String)(execute: NamedDB => A): A = using(NamedDB(Symbol(poolName)))(execute)

}
